package com.ht.module.bus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.abnormal.HtException;
import com.ht.config.dataAuth.DataScope;
import com.ht.constant.BusConstant;
import com.ht.constant.DicConstants;
import com.ht.module.bus.entity.TTransportationCompanyInformation;
import com.ht.module.bus.entity.TVehicleInformation;
import com.ht.module.bus.entity.TVehicleRouteResponsibility;
import com.ht.module.bus.mapper.TTransportationCompanyInformationMapper;
import com.ht.module.bus.mapper.TVehicleInformationMapper;
import com.ht.module.bus.mapper.TVehicleRouteResponsibilityMapper;
import com.ht.module.bus.service.TVehicleInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.module.bus.service.TVehicleRouteResponsibilityService;
import com.ht.util.CommMethod;
import com.ht.util.Pager;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 承运企业车辆信息表 服务实现类
 * </p>
 *
 * @author hejialun
 * @since 2024-07-29
 */
@Service
public class TVehicleInformationServiceImpl extends ServiceImpl<TVehicleInformationMapper, TVehicleInformation> implements TVehicleInformationService {
    @Resource
    private TTransportationCompanyInformationMapper transportationCompanyInformationMapper;
    @Resource
    private TVehicleRouteResponsibilityMapper vehicleRouteResponsibilityMapper;
    @Resource
    private TVehicleRouteResponsibilityService vehicleRouteResponsibilityService;

    @Override
    public Pager<TVehicleInformation> findPageAuth(Pager<TVehicleInformation> pager, TVehicleInformation en) {
        QueryWrapper<TVehicleInformation> qw = getQW(en);
        baseMapper.findPageAuth(pager,qw,new DataScope().initOrder(pager));
        handleRoute(pager.getRecords());
        return pager;
    }

    @Override
    public List<TVehicleInformation> findListAuth(TVehicleInformation en) {
        QueryWrapper<TVehicleInformation> qw = getQW(en);
        List<TVehicleInformation> list = baseMapper.findListAuth(qw, new DataScope());
        handleRoute(list);
        return list;
    }

    @Override
    public void add(TVehicleInformation en) {
        //判断车牌是否存在
        TVehicleInformation row = baseMapper.selectById(en.getVehicleLicenseLate());
        if(BeanUtil.isNotEmpty(row)){
            throw new HtException("车牌已经存在！");
        }
        baseMapper.insert(en);

    }

    @Override
    public List<TTransportationCompanyInformation> findVehicleBuildTree(TVehicleInformation en) {
        QueryWrapper<TVehicleInformation> qw = getQW(en);
        List<TVehicleInformation> vehicles = baseMapper.findListAuth(qw, new DataScope());
        if(vehicles.isEmpty()){
            return new ArrayList<>();
        }

        //企业编码集合
        List<String> companyCodes = vehicles.stream().map(TVehicleInformation::getCompanyCode).collect(Collectors.toList());
        //企业集合
        List<TTransportationCompanyInformation> companys = transportationCompanyInformationMapper.selectList(
                new QueryWrapper<TTransportationCompanyInformation>()
                        .in("company_code", companyCodes)
        );

        for (TTransportationCompanyInformation company : companys) {
            //过滤出当前企业下的车辆
            company.setVehicles(
                    vehicles.stream()
                            .filter(x -> StrUtil.equals(x.getCompanyCode(), company.getCompanyCode()))
                            .collect(Collectors.toList())
            );
        }
        return companys;
    }


    /**
     * 处理车辆对应的路线
     * @param list
     */
    private void handleRoute(List<TVehicleInformation> list){
        List<String> licenseLates = list.stream().map(TVehicleInformation::getVehicleLicenseLate).collect(Collectors.toList());
        if(licenseLates.isEmpty()){
            return;
        }

        //查询出当前车辆关联的路线
        List<TVehicleRouteResponsibility> routes = vehicleRouteResponsibilityMapper.findListAuth(
                new QueryWrapper<TVehicleRouteResponsibility>()
                        .eq("state", DicConstants.State.ENABLE)
                        .in("vehicle_license_late", licenseLates), null
        );

        for (TVehicleInformation row : list) {
            List<TVehicleRouteResponsibility> collect = routes.stream().filter(x -> StrUtil.equals(x.getVehicleLicenseLate(), row.getVehicleLicenseLate())).collect(Collectors.toList());
            row.setRouteEns(collect);
        }
    }


    @Override
    public List<String> findCarBrand(String carBrand) {
        QueryWrapper<TVehicleInformation> qw=new QueryWrapper<>();
        if(StrUtil.isNotEmpty(carBrand)){
            qw.like("car_brand",carBrand);
        }

        List<TVehicleInformation> vehicleInformations = baseMapper.selectList(qw);
        Set<String> carbrands =
                vehicleInformations.stream().map(TVehicleInformation::getCarBrand).collect(Collectors.toSet());
        return new ArrayList<>(carbrands);
    }

    @Override
    public void editById(TVehicleInformation en) {
        baseMapper.updateById(en);
        //删除历史路线
        vehicleRouteResponsibilityMapper.delete(
                new QueryWrapper<TVehicleRouteResponsibility>()
                        .eq("vehicle_license_late",en.getVehicleLicenseLate())
        );


        List<TVehicleRouteResponsibility> list=new ArrayList<>();
        //插入新的路线
        if(BeanUtil.isNotEmpty(en.getRouteEns())){
            for (TVehicleRouteResponsibility route : en.getRouteEns()) {
                TVehicleRouteResponsibility row=new TVehicleRouteResponsibility()
                        .setVehicleLicenseLate(en.getVehicleLicenseLate())
                        .setRouteCode(route.getRouteCode())
                        .setDistrictCode(route.getDistrictCode());
                CommMethod.beanCreate(row);
                list.add(row);
            }
        }
        vehicleRouteResponsibilityService.saveBatch(list);

    }

    private QueryWrapper<TVehicleInformation> getQW(TVehicleInformation en){
        QueryWrapper<TVehicleInformation> qw=new QueryWrapper<>();
        if(StrUtil.isNotEmpty(en.getCompanyCode())){
            qw.eq("tab.company_code",en.getCompanyCode());
        }
        if(StrUtil.isNotEmpty(en.getCompanyName())){
            qw.like("tab.company_name",en.getCompanyName());
        }
        if(StrUtil.isNotEmpty(en.getVehicleLicenseLate())){
            qw.eq("tab.vehicle_license_late",en.getVehicleLicenseLate());
        }
        if(StrUtil.isNotEmpty(en.getCarBrand())){
            qw.like("tab.car_Brand",en.getCarBrand());
        }

        if(StrUtil.isNotEmpty(en.getState())){
            qw.like("tab.state",en.getState());
        }
        qw.eq("tab.del_flag", BusConstant.DEL_FLAG_N);
        qw.orderByDesc("tab.create_date");
        return qw;
    }
}
